package com.coderg.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.coderg.gmall.model.product.*;
import com.coderg.gmall.product.mapper.*;
import com.coderg.gmall.product.service.ItemService;
import com.coderg.gmall.product.service.ManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author CoderG
 * @Date 2025/5/22 19:32
 **/
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    SkuInfoMapper skuInfoMapper;
    @Autowired
    SkuImageMapper skuImageMapper;
    @Autowired
    ManageService manageService;
    @Autowired
    BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;

    /**
     * 查询sku详情
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuInfo getSkuInfo(Long skuId) {

        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo == null) {
            return null;
            // throw new RuntimeException("商品不存在");
        }

        //查询sku图片
        LambdaQueryWrapper<SkuImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SkuImage::getSkuId, skuId);
        List<SkuImage> skuImages = skuImageMapper.selectList(wrapper);
        skuInfo.setSkuImageList(skuImages);


        return skuInfo;
    }

    /**
     * 查询目录视图
     *
     * @param category3Id
     * @return
     */
    @Override
    public BaseCategoryView getBaseCategory(Long category3Id) {
        //sku分类信息     通过三级分类id查询二级分类以及一级分类
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        if (baseCategoryView == null) {
            throw new RuntimeException("baseCategoryView不存在");
        }
        return baseCategoryView;
    }

    /**
     * 获取价格
     *
     * @param skuId
     * @return
     */
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo == null) {
            throw new RuntimeException("商品不存在");
        }
        return skuInfo.getPrice();
    }

    /**
     * 通过skuId,spuId查询 销售属性和值以及标记当前选中的销售属性值
     *
     * @param spuId
     * @param skuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> getSpuAttrValueBy(Long spuId, Long skuId) {
        if (spuId == null || skuId == null) {
            return null;
        }
        return spuSaleAttrMapper.selectSkuBySpuIdAndSkuID(spuId, skuId);
    }

    /**
     * 获取销售属性 和具体商品sku值的对应关系 键值对关系返回  sku-->sale_attr_value_id
     *
     * @param spuId
     * @return
     */
    @Override
    public Map<String, String> getSkuAndSaleBySpuId(Long spuId) {
        List<Map> maps = skuInfoMapper.selectSkuAndSaleBySpuId(spuId);
        HashMap<String, String> hashMap = new HashMap<>();
        for (Map map : maps) {
            String sku_id = map.get("sku_id").toString();
            String sale_attr_value_id = (String) map.get("sale_attr_value_id");
            hashMap.put(sku_id, sale_attr_value_id);
        }
        return hashMap;
    }

    /**
     * 获取首页所有目录集合
     *
     * @return
     */
    @Override
    public List<JSONObject> getFirstCategory123() {

        List<BaseCategoryView> baseCategoryViews =
                baseCategoryViewMapper.selectList(null);
        Map<Long, List<BaseCategoryView>> baseCategory1View = baseCategoryViews.stream().collect(Collectors.groupingBy(
                BaseCategoryView::getCategory1Id));
        //结果集合  //List<map<"分类id",分类值 ，{二级分类List<map<"分类id",分类值,{三级分类List<map<"分类id",分类值>>} >>}  >>
        ArrayList<JSONObject> jsonObjects = new ArrayList<>();
        baseCategory1View.entrySet().stream().forEach(baseCategory1 -> {
            //获取一级分类id
            Long baseCategory1Id = baseCategory1.getKey();
            //获取一级分类name
            List<BaseCategoryView> baseCategory1Views = baseCategory1.getValue();
            String category1Name = baseCategory1Views.get(0).getCategory1Name();
            //获取一级分类包含的二级分类集合  二级分类List<map<"分类id",分类值,{三级分类List<map<"分类id",分类值>>} >>
            Map<Long, List<BaseCategoryView>> baseCategory2View =
                    baseCategory1Views.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            List<JSONObject> jsonObject2List = baseCategory2View.entrySet().stream().map(baseCategory2 -> {
                //获取二级分类id
                Long baseCategory2Id = baseCategory2.getKey();
                //获取二级分类name
                List<BaseCategoryView> baseCategory2Views = baseCategory2.getValue();
                String category2Name = baseCategory2Views.get(0).getCategory2Name();
                //获取二级分类包含的三级分类集合 三级分类List<map<"分类id",分类值>>
                List<JSONObject> jsonObject3List = baseCategory2Views.stream().map(baseCategory3 -> {
                    JSONObject jsonObject = new JSONObject();
                    //获取三级分类id
                    Long category3Id = baseCategory3.getCategory3Id();
                    //获取三级分类name
                    String category3Name = baseCategory3.getCategory3Name();
                    jsonObject.put("categoryId", category3Id);
                    jsonObject.put("categoryName", category3Name);
                    return jsonObject;
                }).collect(Collectors.toList());
                //
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("categoryId", baseCategory2Id);
                jsonObject.put("categoryName", category2Name);
                jsonObject.put("categoryList", jsonObject3List);
                return jsonObject;
            }).collect(Collectors.toList());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("categoryId", baseCategory1Id);
            jsonObject.put("categoryName", category1Name);
            jsonObject.put("categoryList", jsonObject2List);
            jsonObjects.add(jsonObject);

        });
        return jsonObjects;
    }


    /**
     * 获取品牌详情B
     *
     * @param tmId
     * @return
     */
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        BaseTrademark baseTrademark = baseTrademarkMapper.selectById(tmId);
        return baseTrademark;
    }

    /**
     * 根据skuId查询商品的平台属性
     *
     * @param skuId
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        //多表查询  sku_attr_value base_attr_info base_attr_value

        // List<BaseAttrInfo> baseAttrInfoList = skuAttrValueMapper.selectOnSkuId(skuId);
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectOnSkuId(skuId);
        return baseAttrInfoList;
    }

    /**
     * 扣减库存
     *
     * @param stockpile
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean decreaseStockpile(Map<Long, Integer> stockpile) {
        stockpile.entrySet().stream().forEach(entry -> {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            int i = skuInfoMapper.updateStock(skuId, num);
            if (i <= 0) {
                throw new RuntimeException("扣减库存失败");
            }
            ;
        });
        return true;
    }

    /**
     * 回退库存
     *
     * @param stockMap
     * @return
     */
    @Override
    public boolean rollbackStock(Map<String, String> stockMap) {

        stockMap.entrySet().stream().forEach(entry -> {
            Long skuId = Long.valueOf(entry.getKey());
            Integer num = Integer.valueOf(entry.getValue());
            int i = skuInfoMapper.addStock(skuId, num);

            if (i <= 0) {
                throw new RuntimeException("扣减库存失败");
            }
        });
        return true;

        // int affected = skuInfoMapper.update(null,
        //          new UpdateWrapper<SkuInfo>()
        //                 .setSql("stock = stock + {0}", num)
        //                 .eq("id", skuId)
        // );

    }
}
